﻿namespace WSBackup
{
    using System;
    using System.Drawing;
    using System.Runtime.InteropServices;

    /// <summary>
    /// TODO: Update summary.
    /// </summary>
    public class SHGetFileInfo
    {
        [StructLayout(LayoutKind.Sequential)]
        public struct SHFILEINFO
        {
            public IntPtr hIcon;
            public IntPtr iIcon;
            public uint dwAttributes;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
            public string szDisplayName;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
            public string szTypeName;
        };

        public class Win32
        {
            public const uint SHGFI_ICON = 0x100;
            public const uint SHGFI_LARGEICON = 0x0; // 'Large icon
            public const uint SHGFI_SMALLICON = 0x1; // 'Small icon
            [DllImport("shell32.dll")]
            public static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, uint cbSizeFileInfo, uint uFlags);
        }


        public static IconStruct GetFileIcons(string fName)
        {
            var shinfo = new SHFILEINFO();
            if (Win32.SHGetFileInfo(fName, 0, ref shinfo, (uint)Marshal.SizeOf(shinfo), Win32.SHGFI_ICON | Win32.SHGFI_SMALLICON) == IntPtr.Zero)
            {
                return null;
            }

            var ret = new IconStruct { IconSmall = Icon.FromHandle(shinfo.hIcon), iIcon = shinfo.iIcon.ToInt32() };

            if (Win32.SHGetFileInfo(fName, 0, ref shinfo, (uint)Marshal.SizeOf(shinfo), Win32.SHGFI_ICON | Win32.SHGFI_LARGEICON) != IntPtr.Zero)
            {
                ret.IconLarge = Icon.FromHandle(shinfo.hIcon);
            }

            return ret;
        }
        
        public class IconStruct
        {
            public int iIcon;
            public Icon IconLarge;
            public Icon IconSmall;
        }
    }
}
